package org.company.earth.utils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

public class FileUtil {
    /**
     * 读取文件最后的完整一行
     * @method readLastLine
     * @param uri
     * @return
     * @throws IOException
     */
    public static String readLastLine(RandomAccessFile raf) throws IOException {
        String line = null;
        long len = raf.length();
        if(len == 0) {
            raf.close();
            return "";
        }
        
        long pos = len-1;
        byte b = 0;
        while(pos > 0) {
            raf.seek(--pos);
            b = raf.readByte();
            if(b == '\n') {
                line = raf.readLine();
                break;
            }
        }
        raf.close();
        return line;
    }
    
    /**
     * 读取raf文件上一行
     * @method readPrevLine
     * @param raf
     * @return
     * @throws IOException
     */
    public static String readPrevLine(RandomAccessFile raf) throws IOException {
        long begin = raf.getFilePointer();
        long pos = begin;
        byte b = 0;
        String line = null;
        while(pos > 0) {
            raf.seek(--pos);
            b = raf.readByte();
            if(b == '\n' || raf.getFilePointer() == 1) {
                System.out.println(pos + ":" + raf.getFilePointer());
                line = raf.readLine();
                raf.seek(pos);
                break;
            }
        }
        return line;
    }
}
